<?php
/**
 * Created by PhpStorm.
 * User: kevin
 * Date: 2015/7/8
 * Time: 15:09
 */
namespace Admin\Controller;
use Admin\Model\AuthRuleModel;
use Admin\Model\AuthGroupModel;

class AuthManagerController extends AdminController{
    /*
     * 权限设置首页
     */
    public function index(){
        $AuthGroup = M('AuthGroup');
        $map['is_true']=array('neq','0');
        $list = $this->lists($AuthGroup,$map);
        $list = int_to_string($list);
        $this->assign( 'list', $list );
        $this->assign('meta_title', '用户组管理');
        $this->display();
    }

    //成员授权页面
    public function user($group_id){
        if(empty($group_id)){
            $this->error('参数错误');
        }
        $auth_group = M('AuthGroup')->where( array('status'=>array('eq','1'),'type'=>AuthGroupModel::TYPE_ADMIN,'sid'=>array('EQ',0)))
            ->getfield('id,id,title,rules');
        $prefix   = C('DB_PREFIX');
        $l_table  = $prefix.(AuthGroupModel::MEMBER);
        $r_table  = $prefix.(AuthGroupModel::AUTH_GROUP_ACCESS);
        $model    = M()->table( $l_table.' m' )->join ( $r_table.' a ON m.id=a.uid' );
        $_REQUEST = array();
        $list = $this->lists($model,array('a.group_id'=>$group_id,'m.status'=>array('egt',0)),'m.id asc','m.id,m.username,m.status');
        int_to_string($list);
        $this->assign( '_list',     $list );
        $this->assign('auth_group', $auth_group);
        $this->assign('this_group', $auth_group[(int)$_GET['group_id']]);
        $this->meta_title = '成员授权';
        $this->display();
    }


    //用户解除授权
    public function removeFromGroup(){
        $uid = I('uid');
        $gid = I('group_id');
        if( $uid==UID ){
            $this->error('不允许解除自身授权');
        }
        if( empty($uid) || empty($gid) ){
            $this->error('参数有误');
        }
        $AuthGroup = D('AuthGroup');
        if( !$AuthGroup->find($gid)){
            $this->error('用户组不存在');
        }
        if ( $AuthGroup->removeFromGroup($uid,$gid) ){
            $this->success('操作成功');
        }else{
            $this->error('操作失败1');
        }
    }

    /*
     * 将用户添加到用户组的编辑页面
     */
    public function group(){
        $uid            =   I('id');
        $auth_groups    =   D('AuthGroup')->getAllGroups();
        $user_groups    =   AuthGroupModel::getUserGroup($uid);
        $ids = array();
        foreach ($user_groups as $value){
            $ids[]      =   $value['group_id'];
        }
        $map['id'] = $uid;
        $nickname       =   D('User')->where($map)->getField('username');
        $this->assign('nickname',   $nickname);
        $this->assign('auth_groups',$auth_groups);
        $this->assign('user_groups',implode(',',$ids));
        $this->meta_title = '用户组授权';
        $this->display();
    }

    //添加用户组页面
    public function createGroup(){
        $module=M('Menus')->select();
        if ( empty($this->auth_group) ) {
            $this->assign('auth_group',array('title'=>null,'id'=>null,'description'=>null,'rules'=>null,));//排除notice信息
        }
        $this->assign('module',$module);
        $this->meta_title = '新增用户组';
        $this->display('editgroup');
    }
    //编辑用户组的方法
    public function editgroup(){
        $module=M('Menus')->select();
        $auth_group = M('AuthGroup')->where(array('id'=>$_GET['id']))->find();
//        var_dump($auth_group);die;
        $this->assign('module',$module);
        $this->assign('auth_group',$auth_group);
        $this->meta_title = '编辑用户组';
        $this->display();
    }
    //添加用户组权限
    public function writeGroup(){
        if (isset($_POST['rules'])) {
            sort($_POST['rules']);
            $_POST['rules'] = implode(',', array_unique($_POST['rules']));
        }else{
            $_POST['rules']='';
        }
        $_POST['type']   =  AuthGroupModel::TYPE_ADMIN;
        $AuthGroup       =  D('AuthGroup');
        $data = $AuthGroup->create();
        if ( $data ) {
            if ( empty($data['id']) ) {
                $r = $AuthGroup->add();
                //添加用户组的学校权限
//                D('SchoolList')->addgroupId($r);
            }else{
                $r = $AuthGroup->save();
            }
            if($r===false){
                $this->error('操作失败2'.$AuthGroup->getError());
            } else{
                $this->success('操作成功!',U('index'));
            }
        }else{
            $this->error('操作失败3'.$AuthGroup->getError());
        }
    }



    /*
     * 将用户添加到用户组
     */
    public function addToGroup(){
        $text = I('text');
        $Select_mess = M('User')->where(array('username' => array('in', $text)))->select();
        if ($Select_mess) {
            $uids = array();
            foreach ($Select_mess as $key => $vo) {
                $uids[] = $vo['id'];
            }
            $uid = implode(',', $uids);
        } else {
            $uid = I('text');
            $uids=explode(",",$uid);
        }
        $gid = I('group_id');
        if (empty($uid)) {
            $this->error('参数有误');
        }
        $AuthGroup = D('AuthGroup');
        if ($uid) {
            if (is_administrator($uid)) {
                $this->error('该用户为超级管理员');
            }
            $map['id'] = array('IN', $uid);
            $uid_ = M('User')->where($map)->select();
            if (!$uid_) {
                $this->error('用户不存在');
            } else {
                $arr = M('auth_group_access')->where(array('group_id' => $gid))->select();
                $uid_g = array();
                foreach ($arr as $key => $item) {
                    $uid_g[] = $item['uid'];
                }
                $count = 0;
                for ($i = 0; $i < count($uid_g); ++$i)
                    if (in_array($uid_g[$i], $uids))
                        ++$count;
                if ($count > 0) {
                    $this->error('用户已被添加');
                } else {
                    if ($gid && !$AuthGroup->checkGroupId($gid)) {
                        $this->error($AuthGroup->error);
                    }
                    if ($AuthGroup->addToGroup($uids, $gid)) {
                        $this->success('操作成功');
                    } else {
                        $this->error($AuthGroup->getError());
                    }
                }
            }
        }
    }
    //修改状态
    public function changeStatus($method=null){
        $id   = intval(I('id'));
        $list = M('AuthGroup')->find($id);
        if ( empty($list) )
        {
            $this->error('用户组不存在信息!');
        }
        switch ( strtolower($method) ){
            case 'forbidgroup':
                $this->forbid('AuthGroup');
                break;
            case 'resumegroup':
                $this->resume('AuthGroup');
                break;
            case 'deletegroup':
                $this->delete('AuthGroup');
                break;
            default:
                $this->error($method.'参数非法');
        }
    }
    //访问授权
    public function access(){
        $id =(int)I('group_id');
        $module = $this->getModuleByGroupID($id);
        $this->updateRules($module);
        $auth_group = M('AuthGroup')->where(array('status' => array('egt', '0'), 'module' => $module, 'type' => AuthGroupModel::TYPE_ADMIN))
            ->getfield('id,id,title,rules');
        $node_list = $this->returnNodes($module);

        $map = array('module' => $module, 'type' => AuthRuleModel::RULE_MAIN, 'status' => 1);
        $main_rules = M('AuthRule')->where($map)->getField('name,id');
        $map = array('module' => $module, 'type' => AuthRuleModel::RULE_URL, 'status' => 1);
        $child_rules = M('AuthRule')->where($map)->getField('name,id');
        $this->assign('main_rules', $main_rules);
        $this->assign('auth_rules', $child_rules);
        $this->assign('node_list', $node_list);
        $this->assign('auth_group', $auth_group);
        $this->assign('this_group', $auth_group[$id]);
        $this->meta_title = '访问授权';
        $this->display('managergroup');
    }

    /*
     * 根据用户组ID获取用户组的模块
     */
    private function getModuleByGroupID($id){
        $where['id'] = $id;
        return M('AuthGroup')->where($where)->getfield('module');
    }
    /*
     * 禁用用户
     * $model 模块
     * $map条件
     */
    protected function forbid(){
        $data['status'] = 0;
        $map['id'] = I('id',0);
        $res = M('AuthGroup')->where($map)->data($data)->save();
        if($res){
            $this->success('状态禁用成功');
        }else{
            $this->error('状态禁用失败');
        }
    }

    /*
     * 删除用户
     */
    protected function delete()
    {
        $data['status'] = -1;
        $map['id'] = I('id', 0);
        $res = M('AuthGroup')->data($data)->where($map)->save();
        if ($res) {
            $this->success('用户删除成功');
        } else {
            $this->error('用户删除失败');
        }
    }

    /*
     * 启用用户
     */
    protected function resume(){
        $data['status'] =1;
        $map['id'] = I('id',0);
        $res = M(AuthGroup)->data($data)->where($map)->save();
        if($res){
            $this->success('启用用户成功');
        }else{
            $this->error('启用用户失败');
        }
    }

    public function updateRules($module){
        //需要新增的节点必然位于$nodes
        $nodes    = $this->returnNodes($module,false);
        $AuthRule = M('AuthRule');
        $map      = array('module'=>$module,'type'=>array('in','1,2'));//status全部取出,以进行更新
        //需要更新和删除的节点必然位于$rules
        $rules    = $AuthRule->where($map)->order('name')->select();
        //构建insert数据
        $data     = array();//保存需要插入和更新的新节点
        foreach ($nodes as $value){
            $temp['name']   = $value['url'];
            $temp['title']  = $value['title'];
            $temp['module'] = $module;
            if($value['pid'] >0){
                $temp['type'] = AuthRuleModel::RULE_URL;
            }else{
                $temp['type'] = AuthRuleModel::RULE_MAIN;
            }
            $temp['status']   = 1;
            $data[strtolower($temp['name'].$temp['module'].$temp['type'])] = $temp;//去除重复项
        }

        $update = array();//保存需要更新的节点
        $ids    = array();//保存需要删除的节点的id
        foreach ($rules as $index=>$rule){
            $key = strtolower($rule['name'].$rule['module'].$rule['type']);
            if ( isset($data[$key]) ) {//如果数据库中的规则与配置的节点匹配,说明是需要更新的节点
                $data[$key]['id'] = $rule['id'];//为需要更新的节点补充id值
                $update[] = $data[$key];
                unset($data[$key]);
                unset($rules[$index]);
                unset($rule['condition']);
                $diff[$rule['id']]=$rule;
            }elseif($rule['status']==1){
                $ids[] = $rule['id'];
            }
        }
        if ( count($update) ) {
            foreach ($update as $k=>$row){
                if ( $row!=$diff[$row['id']] ) {
                    $AuthRule->where(array('id'=>$row['id']))->save($row);
                }
            }
        }
        if ( count($ids) ) {
            $AuthRule->where( array( 'id'=>array('IN',implode(',',$ids)) ) )->save(array('status'=>-1));
            //删除规则是否需要从每个用户组的访问授权表中移除该规则?
        }
        if( count($data) ){
            $AuthRule->addAll(array_values($data));
        }
        if ( $AuthRule->getDbError() ) {
            trace('['.__METHOD__.']:'.$AuthRule->getDbError());
            return false;
        }else{
            return true;
        }
    }

    final protected function returnNodes($module, $tree = true)
    {
        static $tree_nodes = array();
        if ($tree && !empty($tree_nodes[(int)$tree])) {
            return $tree_nodes[$tree];
        }
        $where['module'] = $module;
        if ((int)$tree) {
            $list = M('Menu')->where($where)->field('id,pid,title,url,tip,hide')->order('sort asc')->select();
            foreach ($list as $key => $value) {
                if (stripos($value['url'], $module) !== 0) {
                    $list[$key]['url'] = $module . '/' . $value['url'];
                }
            }
            $nodes = list_to_tree($list, $pk = 'id', $pid = 'pid', $child = 'operator', $root = 0);
            foreach ($nodes as $key => $value) {
                if (!empty($value['operator'])) {
                    $nodes[$key]['child'] = $value['operator'];
                    unset($nodes[$key]['operator']);
                }
            }
        } else {
            $nodes = M('Menu')->where($where)->field('title,url,tip,pid')->order('sort asc')->select();
            foreach ($nodes as $key => $value) {
                if (stripos($value['url'], $module) !== 0) {
                    $nodes[$key]['url'] = $module . '/' . $value['url'];
                }
            }
        }
        $tree_nodes[(int)$tree] = $nodes;
        return $nodes;
    }
}